/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        vector<int> v;
        int sum=0,sump=0;
        queue<TreeNode*> q;
        if(root) q.push(root);
        sum=1;
        while(!q.empty()){
            TreeNode* cur = q.front();
            v.push_back(cur->val);
            q.pop();
            sum--;
            if(cur->left){
                q.push(cur->left);
                sump++;
            }
            if(cur->right){
                q.push(cur->right);
                sump++;
            }
            if(sum==0){
                result.push_back(v);
                v.clear();
                sum=sump;
                sump=0;
            }
        }
        return result;
    }
};